import random
import logging
logger = logging.getLogger('django')
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views import View


#验证码生成
from django_redis import get_redis_connection

from meiduo_malll.libs.captcha.captcha import captcha


class VerifyCodeView(View):
    def get(self,request,uuid):
        text,image=captcha.generate_captcha()
        redis_conn=get_redis_connection('verify_code')
        redis_conn.setex(uuid,300,text)
        # 4.返回(图片)
        return HttpResponse(image,content_type='image/jpg')

class SMSVerification(View):
    def get(self,request,mobile):
        redis_conn = get_redis_connection('verify_code')
        send_flag=redis_conn.get('send_flag%s'%mobile)
        if send_flag:
            return JsonResponse({'code':'400',
                                 'errmsg':'发送短信验证码过于频繁'})
        #验证码
        image_code=request.GET.get('image_code')
        #uuid
        uuid=request.GET.get('image_code_id')
        # 2. 校验参数
        if not all([image_code, uuid]):
            return JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})
        verify_code=redis_conn.get(uuid)
        if verify_code is None:
            return JsonResponse({'code':400,
                                 'errmsg':'验证码失效'})
        # 5. 删除图形验证码，避免恶意测试图形验证码
        try:
            redis_conn.delete('%s' % uuid)
        except Exception as e:
            logger.error(e)

        if verify_code.decode().lower()!=image_code.lower():
            return JsonResponse({'code':400,
                                 'errmsg':'输入验证码错误'})
        sms_code='%06d'%random.randint(0,999999)
        logger.info(sms_code)
        redis_conn.setex('%s'%mobile,300,sms_code)
        redis_conn.setex('send_flag%s'%mobile,60,1)
        return JsonResponse({'code':0,
                             'errmsg':'ok'})

